/**
 * Author:  LiShibin.
 * Date:    2016/12/12.
 * File：   .
 */
let HmacMD5 = require('crypto-js/hmac-md5.js')

/***
 * 获取签名
 * @param sec 是否加密
 * @param url 请求地址
 * @param ak accessTokenKey
 * @param at accessToken
 * @param ct 参数
 * @return {Promise.<*>}
 * 说明：async函数返回的是promise对象
 */
async function getSign (ak, at, ct, sec, url) {
  let clientId = window.localStorage.getItem('clientId') || '2E7966B47EA04112BBC03F3B9992E6F7'
  let pa = at + (sec ? [clientId, ak, ct, sec, url] : [clientId, ak, ct])
    .sort().join('').replace(/\t|\r|\n/g, '') + at
  // console.log('ct', ct)
  let sign
  try {
    sign = HmacMD5(pa, at).toString().toUpperCase()
  } catch (e) {
    console.log('签名错误')
    console.log(e)
  }
  return sign
}
/**
 *  针对obj的key进行排序方法
 */
function sortObjectKeys (obj) {
  var tmp = {}
  Object.keys(obj).sort().forEach(function (k) {
    tmp[k] = obj[k]
  })
  return tmp
}
/***
 * 获取头部
 * @param url
 * @param data
 * @return {Promise.<{Content-Type: string, ehome-head-params: string}>}
 * 说明：async函数返回的是promise对象
 */
async function getHead (type, url, data) {
  let args = []
  // let userId = window.localStorage.getItem('userId')
  // args.push(userId)
  // args.push(url)
  // args.push('')
  // let header = {
  //   'Content-Type': 'application/octet-stream',
  //   'ehome-head-params': args.join(';')
  // }
  let clientId = window.localStorage.getItem('clientId') || '2E7966B47EA04112BBC03F3B9992E6F7'
  let ct = JSON.stringify(sortObjectKeys(data))
  let ak = window.localStorage.getItem('accessTokenKey') || '11EA5CF81B4563E772A2EA64888CAF40'
  let at = window.localStorage.getItem('accessToken') || 'A0AB570E262BB108FBB80CBF3BE918CE'
  let header
  switch (type) {
    case 'inner':
      let userId = window.localStorage.getItem('userId')
      args.push(userId)
      args.push(url)
      args.push('')
      header = {
        'Content-Type': 'application/octet-stream',
        'ehome-head-params': args.join(';')
      }
      break
    case 'oauth':
      args.push(clientId)
      args.push(url)
      args.push('')
      header = {
        'Content-Type': 'application/octet-stream',
        'ehome-head-params': args.join(';')
      }
      break
    case 'login':
      args.push(clientId)
      args.push('')
      header = {
        'Accept': '*/*',
        'skynet-head-params': args.join(';')
      }
      break
    case 'swagger':
      let sign
      sign = await getSign(ak, at, ct)
      args.push(clientId)
      args.push(ak)
      args.push(sign)
      args.push('')
      header = {
        'Accept': '*/*',
        'skynet-head-params': args.join(';')
      }
      break
    default:
      break
  }
  return header
}

export default getHead
